package com.zyp.jobseeker.controller;

import com.zyp.jobseeker.entity.Enterprise;
import com.zyp.jobseeker.entity.Student;
import com.zyp.jobseeker.entity.User;
import com.zyp.jobseeker.enums.UserRole;
import com.zyp.jobseeker.enums.UserStatus;
import com.zyp.jobseeker.mapper.EnterpriseMapper;
import com.zyp.jobseeker.service.UserService;
import com.zyp.jobseeker.utils.JwtUtil;
import com.zyp.jobseeker.utils.PasswordUtil;
import com.zyp.jobseeker.utils.ResultUtil;
import com.zyp.jobseeker.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证Controller
 * 处理用户登录、注册等认证相关请求
 */
@RestController
@RequestMapping("/api")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private PasswordUtil passwordUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    /**
     * 学生用户注册
     */
    @PostMapping("/register/student")
    public ResultUtil<?> registerStudent(@RequestBody Map<String, Object> userInfo) {
        // 📌 添加调试日志：记录请求到达
        System.out.println("[Auth Controller] 🎯 Received student registration request");
        System.out.println("[Auth Controller] 📥 Request data: " + userInfo);
        
        try {
            // 验证必要字段
            if (userInfo.get("username") == null || userInfo.get("password") == null || 
                userInfo.get("name") == null) {
                // 📌 添加调试日志：验证失败
                System.out.println("[Auth Controller] ❌ Validation failed: Missing required fields");
                return ResultUtil.fail(400, "用户名、密码和姓名是必填项");
            }

            // 创建用户实体
            User user = new User();
            String username = (String) userInfo.get("username");
            user.setUsername(username);
            
            // 检查用户名是否已存在
            if (username != null && !username.isEmpty() && userService.findByUsername(username) != null) {
                // 📌 添加调试日志：用户名已存在
                System.out.println("[Auth Controller] ❌ Registration failed: Username already exists - " + username);
                return ResultUtil.fail(400, "该用户名已被注册，请选择其他用户名");
            }
            
            user.setPassword(passwordUtil.encodePassword((String) userInfo.get("password")));
            user.setRole(UserRole.STUDENT);
            user.setStatus(UserStatus.PENDING);
            
            // 创建学生实体
            Student student = new Student();
            student.setName((String) userInfo.get("name"));
            student.setGender((Integer) userInfo.get("gender"));
            // 将字符串格式的日期转换为LocalDate类型
            student.setBirthDate(LocalDate.parse((String) userInfo.get("birthDate")));
            student.setPhone((String) userInfo.get("phone"));
            student.setEmail((String) userInfo.get("email"));
            student.setSchool((String) userInfo.get("school"));
            student.setMajor((String) userInfo.get("major"));
            student.setDegree((String) userInfo.get("degree"));
            // 将字符串格式的日期转换为LocalDate类型
            student.setGraduateDate(LocalDate.parse((String) userInfo.get("graduateDate")));
            student.setProjectExperience((String) userInfo.get("projectExperience"));
            student.setAward((String) userInfo.get("award"));
            student.setCertificate((String) userInfo.get("certificate"));
            
            // 保存用户和学生信息
            Long userId = userService.registerStudent(user, student, user.getPassword());
            if (userId == null) {
                // 📌 添加调试日志：注册失败
                System.out.println("[Auth Controller] ❌ Student registration failed");
                return ResultUtil.fail(500, "学生注册失败,没有插入数据库");
            }
            // 📌 添加调试日志：注册成功
            System.out.println("[Auth Controller] ✅ Student registered successfully with ID: " + userId);
            return ResultUtil.success("注册成功", Map.of("userId", userId));
        } catch (Exception e) {
            // 📌 添加调试日志：捕获异常
            System.err.println("[Auth Controller] 🚨 Exception occurred during student registration:");
            e.printStackTrace();
            return ResultUtil.fail(500, "注册失败: " + e.getMessage());
        }
    }
    
    /**
     * 企业用户注册
     */
    @PostMapping("/register/enterprise")
    public ResultUtil<?> registerEnterprise(@RequestBody Map<String, Object> userInfo) {
        // 📌 添加调试日志：记录请求到达
        System.out.println("[Auth Controller] 🎯 Received enterprise registration request");
        System.out.println("[Auth Controller] 📥 Request data: " + userInfo);
        
        try {
            // 验证必要字段
            if (userInfo.get("username") == null || userInfo.get("password") == null || 
                userInfo.get("enterpriseName") == null) {
                // 📌 添加调试日志：验证失败
                System.out.println("[Auth Controller] ❌ Validation failed: Missing required fields");
                return ResultUtil.fail(400, "用户名、密码和企业名称是必填项");
            }

            // 检查用户名是否已存在
            String username = (String) userInfo.get("username");
            if (username != null && !username.isEmpty() && userService.findByUsername(username) != null) {
                // 📌 添加调试日志：用户名已存在
                System.out.println("[Auth Controller] ❌ Registration failed: Username already exists - " + username);
                return ResultUtil.fail(400, "该用户名已被注册，请选择其他用户名");
            }

            // 检查企业名称是否已存在
            String enterpriseName = (String) userInfo.get("enterpriseName");
            if (enterpriseName != null && !enterpriseName.isEmpty()) {
                // 需要注入EnterpriseMapper来检查企业名称
                Enterprise existingEnterprise = enterpriseMapper.selectByEnterpriseName(enterpriseName);
                if (existingEnterprise != null) {
                    // 📌 添加调试日志：企业名称已存在
                    System.out.println("[Auth Controller] ❌ Registration failed: Enterprise name already exists - " + enterpriseName);
                    return ResultUtil.fail(400, "该企业名称已被注册，请选择其他企业名称");
                }
            }

            // 创建用户实体
            User user = new User();
            user.setUsername(username);
            user.setPassword(passwordUtil.encodePassword((String) userInfo.get("password")));
            user.setRole(UserRole.ENTERPRISE);
            user.setStatus(UserStatus.PENDING);
            
            // 创建企业实体
            Enterprise enterprise = new Enterprise();
            enterprise.setEnterpriseName(enterpriseName);
            enterprise.setIndustry((String) userInfo.get("industry"));
            enterprise.setScale((String) userInfo.get("scale"));
            enterprise.setAddress((String) userInfo.get("address"));
            enterprise.setContact((String) userInfo.get("contact"));

            // 保存用户和企业信息
            Long userId = userService.registerEnterprise(user, enterprise, user.getPassword());
            if (userId == null) {
                // 📌 添加调试日志：注册失败
                System.out.println("[Auth Controller] ❌ Enterprise registration failed");
                return ResultUtil.fail(500, "企业注册失败,没有插入数据库");
            }
            // 📌 添加调试日志：注册成功
            System.out.println("[Auth Controller] ✅ Enterprise registered successfully with ID: " + userId);
            return ResultUtil.success("注册成功", Map.of("userId", userId));
        } catch (Exception e) {
            // 📌 添加调试日志：捕获异常
            System.err.println("[Auth Controller] 🚨 Exception occurred during enterprise registration:");
            e.printStackTrace();
            return ResultUtil.fail(500, "注册失败: " + e.getMessage());
        }
    }

    @PostMapping("/login")
    public ResultUtil<?> login(@RequestBody Map<String, String> loginInfo) {
        System.out.println("[Auth Controller] 🔐 开始处理登录请求");

        // 获取并验证请求参数
        String username = loginInfo.get("username");
        String password = loginInfo.get("password");

        if (username == null || password == null) {
            System.out.println("[Auth Controller] ❌ 请求参数缺失");
            return ResultUtil.fail(400, "用户名或密码未提供");
        }

        System.out.println("[Auth Controller] 📥 收到登录请求 - 用户名: " + username);

        try {
            // 1. 根据用户名查询用户
            User user = userService.findByUsername(username);

            if (user == null) {
                System.out.println("[Auth Controller] ❌ 用户不存在: " + username);
                return ResultUtil.fail(401, "登录失败,没获取到用户信息");
            }
            System.out.println(user);
            System.out.println("[Auth Controller] ✅ 找到用户: " + username +
                    ", 状态: " + user.getStatus() +
                    ", 角色: " + user.getRole());

            // 2. 验证用户状态（非待审核状态）
            if (user.getStatus() == UserStatus.PENDING) {
                System.out.println("[Auth Controller] ❌ 用户处于待审核状态: " + username);
                return ResultUtil.fail(401, "登录失败: 用户待审核");
            }

            // 3. 验证密码匹配
            if (!passwordUtil.matchesPassword(password, user.getPassword())) {
                System.out.println("[Auth Controller] ❌ 密码验证失败: " + username);
                return ResultUtil.fail(401, "登录失败: 密码错误");
            }

            System.out.println("[Auth Controller] ✅ 密码验证成功 - 用户名: " + username);

            // 4. 生成包含用户ID、用户名和角色的Token
            String token = jwtUtil.generateToken(
                    user.getId(),
                    user.getUsername(),
                    user.getRole().getCode()
            );

            System.out.println("[Auth Controller] ✅ Token生成成功 - " +
                    "用户ID: " + user.getId() +
                    ", 角色编码: " + user.getRole().ordinal());

            // 返回成功响应
            return ResultUtil.success(token);

        } catch (Exception e) {
            System.err.println("[Auth Controller] 🚨 登录过程中发生异常: " + e.getMessage());
            e.printStackTrace();
            return ResultUtil.fail(500, "登录失败: 服务器内部错误");
        }
    }
}